
const co = require('co');
const zlib = require('zlib');

var httpRequest = async (opt,httpOnly) => {
    var resolveHandler = function(resolve,res) {
        try{
            resolve(JSON.parse(res));
        }catch(e){
            resolve(res);
        }
    }
    return new Promise(function (resolve, reject) {
        opt.headers = opt.headers || {};
        opt.headers["accept-encoding"] = "gzip,deflate";

        var resChunks = [];
        var http = httpOnly ? require('http') : require('https');
        var req = http.request(opt,function(res){
            res.on('data', function (chunk) {
                resChunks.push(chunk);
            });
            res.on('end',function () {
                var buffer = Buffer.concat(resChunks);
                var encoding = res.headers['content-encoding'];
                if (encoding == 'gzip') {
                    zlib.gunzip(buffer, function(err, decoded) {
                        resolveHandler(resolve,decoded && decoded.toString());
                    });
                } else if (encoding == 'deflate') {
                    zlib.inflate(buffer, function(err, decoded) {
                        resolveHandler(resolve,decoded && decoded.toString());
                    });
                } else {
                    resolveHandler(resolve,buffer.toString());
                }
            });
        });
        req.on('error',function(err){
            console.log('request.error:' + err.message);
            reject(err);
        });
        if (opt.data){
            req.write(opt.data);
        }
        req.end();
    });
}

module.exports = {
    request: httpRequest
}
